<template>
  <a-config-provider :locale="locale" class="main" >
    <a-layout id="components-layout-demo-custom-trigger" >
      <a-layout-sider
        :trigger="null"
        collapsible
        v-model="collapsed"
        width="232" style=" min-height: 200px; overflow-y: auto;"
      >
        <div :class="state.companyName.length > 7?'logo maxLogoCon':'logo '">
          <dl><dt><img :src="state.headerLogo" style="width: 200px"/></dt>
          </dl>
        </div>
        <a-menu mode="inline" theme="dark" :selectedKeys="currentPath" :openKeys="openKeys"
                @openChange="onOpenChange" @click="MenuItem"  >
          <template v-for="item in menuList">
            <sub-menu v-if="item.children.length > 0" :menu-info="item" :key="item.key" />
            <a-menu-item v-else :key="item.key">
              {{ item.title }}
            </a-menu-item>
          </template>
        </a-menu>
      </a-layout-sider>
      <a-layout>
        <a-layout-header style="background: #fff; padding: 0; position: relative">
          <a-icon
            class="trigger"
            :type="collapsed ? 'menu-unfold' : 'menu-fold'"
            @click="()=> collapsed = !collapsed" style="margin-top: 2px;"
          />
          <div class="userInfor">
            <div class="iAbout">
              <a-tooltip placement="top">
                <template slot="title">
                  <span>退出</span>
                </template>
                <a @click="loginout">
                  <em class="iconfont cloudtuichu4"  style="margin-right: 10px; font-weight: bold; font-size: 22px;float: right; margin-top: 0px;"></em>
                </a>
              </a-tooltip>
              <a-tooltip placement="top" v-if="handleStatsFillScreen !== '' && showFillScreen">
                <template slot="title">
                  <span>大屏显示</span>
                </template>
                <a @click="changePage" style=" margin-right: 0px;">
                  <em class="iconfont cloudpmtz"  style="margin-right: 0px; font-weight: bold;float: right; font-size: 22px;margin-top: 0px;"></em>
                </a>
              </a-tooltip>
            </div>
            <a-dropdown>
              <div class="users">
                <div class="userBg">
                  <div class="header_name">
                    <em class="iconfont clouduser"
                        style="color: #5f6772; float: left; margin-right: 5px"></em>
                    {{ loginName }}
                    <em class="iconfont clouddown" style="color: #a0a4ad; font-size: 10px"></em>
                  </div>
                </div>
              </div>
              <a-menu slot="overlay"  class="topDorp">
                <!--<a-menu-item @click="showVersionModal">
                    <em class="iconfont sjrz"
                        style="color: #5f6772; margin-right: 5px; font-size:16px;"></em>
                    版本信息
                </a-menu-item>-->
                <a-menu-item @click="showModal" v-if="curLoginType === 'PSW'">
                  <em class="iconfont cloudxgmm"
                      style="margin-right: 5px; font-size:16px;"></em>
                  修改密码
                </a-menu-item>
                <a-menu-item @click="showPinModal"  v-if="curLoginType === 'UKEY'">
                  <em class="iconfont cloudxgmm"
                      style="margin-right: 5px; font-size:16px;"></em>
                  修改PIN码
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </div>
        </a-layout-header>
        <a-layout-content
          :style="{ margin: '16px', padding: '0', background: '#f1f2f6', minHeight: '280px',maxHeight:'600'}">
          <breadcrumb-nav />
          <router-view />
          <div id="subapp-viewport"></div>
          <!--<iframe name="myiframe" id="myiframe" ref="myiframe"  :src="iframeIp" frameborder="0" width="100%" height="100%"></iframe>-->
        </a-layout-content>
        <edit-password ref="editPass" :defaultPsw="defaultPsw" v-if="curLoginType === 'PSW'"/>
        <edit-pin ref="editPin" v-if="curLoginType === 'UKEY'"/>
        <init-ukey-auth ref="initUkeyAuth" v-if="fristAuthUKey === 'true' && curLoginType === 'UKEY'"/>
        <soft-version ref="softVersion" />
        <div class="spinBox" v-if="spinning">{{spinText}}</div>
      </a-layout>
    </a-layout>
  </a-config-provider>
</template>
<script>
import zhCN from 'ant-design-vue/lib/locale-provider/zh_CN'
import breadcrumbNav from 'module/breadcrumb-nav.vue'
import editPassword from 'module/editPassword.vue'
import softVersion from 'module/softVersion.vue'
import SubMenu from 'module/subMenu'
import editPin from 'module/editPin';
import initUkeyAuth from 'module/initUkeyAuth.vue';
import {start} from 'qiankun';
import store from '@/commontToken'

export default {
  components: {
    'sub-menu': SubMenu,
    breadcrumbNav,
    editPassword,
    softVersion,
    editPin,
    initUkeyAuth,
  },
  inject: [ 'reload' ],
  data () {
    return {
      locale: zhCN,
      currentPath: [],
      collapsed: false,
      title: sessionStorage.getItem ('title'),
      userName: sessionStorage.getItem ('user'),
      loginName: sessionStorage.getItem ('loginName'),
      needMaintain: sessionStorage.getItem ('needMaintain'),
      remindMaintain: sessionStorage.getItem ('remindMaintain'),
      defaultPsw: sessionStorage.getItem ('defaultPsw'),
      openedSubmenuArr: this.$store.state.app.openedSubmenuArr,
      initLocalHost: {
        qccsId: '',
        enabled: '',
        authtime: '',
        funcLevel: '',
        result: '',
        validStatus: '',
        authFileName: ''
      },
      shrink: false,
      perms: {},
      openKeys: [],
      scanUKeyTimer: -1,
      fristAuthUKey: sessionStorage.getItem('initUkey'),
      enalbedPswLogin: sessionStorage.getItem('enalbedPswLogin'),
      curLoginType: sessionStorage.getItem('curLoginType'),
      isDefaultPinCode: sessionStorage.getItem('isDefaultPinCode'),
      curDeviceId: sessionStorage.getItem('deviceId'),
      isFirst:true,
      showFillScreen:false,
      handleStatsFillScreen:'',
      numCount:0,
      spinning:false,
      spinText:'请稍后...',
      iframe :'',
      iframeIp:''
    }
  },
  computed: {
    menuList() {
      return this.$store.state.app.menuList
    },
    rootSubmenuKeys() {
      return this.$store.state.app.rootSubmenuKeys
    },
    cachePage() {
      return this.$store.state.app.cachePage
    },
    curPath() {
      return this.$store.state.app.currentPath // 当前面包屑数组
    },
    qsBackData() {
      return this.$store.state.common.qsBackData
    },
    styleObj() {
      return this.$store.state.user.styleObj
    },
    state() {
      // 如果只需要取某个命名空间下的state，比如 user ，可以加上参数
      // return store.getGlobalState('user')

      // 返回所有的state则不需添加参数
      return store.getGlobalState('styleObj')
    }
  },
  methods: {
    gotoItem(item) {
      history.pushState(null, item, item)
    },
    flashCheckPath() {
      let pathName = this.$route.path
      console.log(pathName)
      for (let k = 0; k < this.menuList.length; k++) {
        var n = this.menuList[k]
        if (n.children.length > 0) {
          n.children.map((item) => {
            if (pathName === item.path) {
              if (item.key.indexOf('.') > -1) {
                this.currentPath = [item.key]
                let indexC = item.key.indexOf('.')
                const openK = item.key.substring(0, indexC)
                this.openKeys = [openK]
              } else {
                this.currentPath = [item.key]
                this.openKeys = [item.key]
              }
            }
          })
        }
      }
      if(this.currentPath.length === 0){
        for (let k = 0; k < this.menuList.length; k++) {
          var m = this.menuList[k]
          if (m.children.length > 0) {
            m.children.map((item) => {
              if (item.children.length > 0) {
                item.children.map((itm) => {
                  if (pathName === itm.path) {
                    if (itm.key.indexOf('.') > -1) {
                      console.log(itm)
                      this.currentPath = [itm.key]
                      let indexC = itm.key.lastIndexOf('.')
                      const openK = itm.key.substring(0, indexC)
                      this.openKeys = [openK]
                      let firstKey = itm.key.indexOf('.')
                      const openFirstKey = itm.key.substring(0, firstKey)
                      this.openKeys.push(openFirstKey)
                    } else {
                      this.currentPath = [itm.key]
                      this.openKeys = [itm.key]
                    }
                  }
                })
              } else {
                if (pathName === item.path) {
                  if (item.key.indexOf('.') > -1) {
                    this.currentPath = [item.key]
                    let indexC = item.key.indexOf('.')
                    const openK = item.key.substring(0, indexC)
                    this.openKeys = [openK]
                  } else {
                    this.currentPath = [item.key]
                    this.openKeys = [item.key]
                  }
                }
              }
            })
          }
        }
        console.log(this.currentPath)
        console.log(this.openKeys)
      }
    },
    _checkPath(data, pathName, arr) {
      data.map((item) => {
        if (pathName === item.meta.title) {
          this.currentPath = [item.meta.key]
          this.openKeys = [item.key]
        } else if (item.children) {
          arr.push(item.meta.key)
          this._checkPath(item.children, pathName, arr)
        }
      })
    },
    MenuItem(item, data) {
      let willpush = true
      let cKey = item.key
      if (this.$route.meta.key === cKey) {
        this.reload()
        return
      }
      let menu = data || this.menuList
      menu.forEach(element => {
        if (willpush) {
          if (element.key === cKey) {
            this.$router.push({
              path: element.path
            })
            this.currentPath = [item.key]
            console.log(this.currentPath)
            console.log(this.openKeys)
          } else if (element.children && element.children.length > 0) {
            this.MenuItem(item, element.children)
          }
        }
      })
    },
    onOpenChange(openKeys) {
      const latestOpenKey = openKeys.find(key => this.openKeys.indexOf(key) === -1)
      if (this.menuList.indexOf(latestOpenKey) === -1) {
        this.openKeys = openKeys
      } else {
        this.openKeys = latestOpenKey ? [latestOpenKey] : []
      }
    },

    init () {
      let _this = this
      _this.$store.commit ('updateMenulist')
      _this.userName = sessionStorage.getItem('user');
      if (_this.curLoginType === 'UKEY') {
        _this.startScanTimer ()
      }
    },
    showModal () {
      this.$refs.editPass.showModal ()
    },


    showVersionModal () {
      this.$refs.softVersion.showModal ()
    },
    loginout () {
      let _this = this
      this.$store.dispatch('getLoginOut', true)
      this.$store.dispatch ('logoutAct').then (response => {
        if (response.code === 0) {
          _this.$store.commit ('clearOpenedSubmenu')
          _this.$store.commit ('logout', this)
          //如果是UKey认证登录，则退出登录设备
          if (_this.curLoginType === 'UKEY') {
            //_this.$axios.get(this.$uurl+'/ukeyauth/logoutDev');
            _this.clearScanTimer ();
          }
          sessionStorage.clear()
          setTimeout (function () {
            _this.$router.push ({
              name: 'login'
            })
          }, 3000)
          window.location.reload ()
        } else {
          this.$message.error (response.message)
        }
      })
    },

    /**
     * Function    : initPermission
     * Description : 初始化权限码
     * Input       : none
     * Return      : none
     */
    initPermission () {
      this.perms = {
        handleStatsFillScreen: this.hasPermission ('homepage:handleStatsFillScreen')
      }
    },
    /**
     * Function    : startScanTimer
     * Description : 开启扫描UKey设备定时器
     * Input       : None
     * Return      : None
     */
    startScanTimer () {
      let _this = this;
      _this.clearScanTimer ();
      if (_this.scanUKeyTimer !== -1) {
        return;
      }

      //开启扫描外接密钥存储设备定时器
      _this.scanUKeyTimer = setInterval (function () {
        _this.$root.qsLib.getDeviceInfo ()
      }, 1 * 1000);
    },

    /**
     * Function    : filterIdentifyUKeyDev
     * Description : 监听鉴权设备，如果鉴权设备被拔出，则退出
     * Input       : None
     * Return      : None
     */
    filterIdentifyUKeyDev() {
      let _this = this;
      //获取系统认证登录方式
      _this.$axios.get (this.$uurl + '/ukeyauth/getCurrentDev').then (response => {
        response = response.data;
        if (response.code === 0 && response.data.currentStatus === '0') {
          return;
        }
        _this.logout ();
      }).catch (e => {
        _this.clearScanTimer ();
        _this.logout ();
      })
    },

    /**
     * Function    : clearScanTimer
     * Description : 关闭扫描UKey设备定时器
     * Input       : None
     * Return      : None
     */
    clearScanTimer () {
      let _this = this
      //关闭定时器
      if (_this.scanUKeyTimer === -1) {
        return
      }
      clearInterval (_this.scanUKeyTimer)
      //console.log("关闭定时器:",_this.scanUKeyTimer)
      _this.scanUKeyTimer = -1
    },

    /**
     * Function    : logout
     * Description :  退出登录
     * Input       : None
     * Return      : None
     */
    logout () {
      let _this = this;
      this.$store.dispatch('getLoginOut', true)
      _this.$store.dispatch('logoutAct').then(response => {
        if (response.code === 0) {
          _this.$store.commit('clearOpenedSubmenu');
          _this.$store.commit('logout', this);

          //如果是UKey认证登录，则退出登录设备
          if (_this.curLoginType === 'UKEY') {
            //_this.$axios.get(this.$uurl+'/ukeyauth/logoutDev');
            _this.clearScanTimer ();
            _this.$root.qsLib.deleteAuthUKeyPinCode()
          }

          setTimeout(function () {
            _this.$router.push({
              name: 'login'
            });
          }, 3 * 1000);
          window.location.reload();
        } else {
          this.$message.error(response.message);
        }
      });
    },

    getSrceenObj(){
      let _this =this
      this.$otherGetParams ('api/sysconfig/getSysConfigByCode', {code: '10000005',serverCode:'micrApp'},'sysconf').then (res => {
        if (res.code === 0) {
          if(JSON.stringify(res.data) !=='{}'&&res.data.paramValue !== ''&&res.data.paramValue !== null && res.data.paramName.indexOf('大屏首页') !== -1 ){
            _this.handleStatsFillScreen = res.data.paramValue
          }else{
            _this.handleStatsFillScreen = ''
          }
        } else {
          _this.$message.error (res.data.message)
        }
      })
    },

    /**
     * Function    : changePage
     * Description : 切换到内页的方法
     * Input       : none
     * Return      : none
     */
    changePage() {
      this.$router.push({
        path: this.handleStatsFillScreen
      }, onComplete => {
      }, onAbort => {
      })
    },

    /**
     * Function    : showPinModal
     * Description :  显示修改PIN码对话框
     * Input       : None
     * Return      : None
     */
    showPinModal() {
      this.$refs.editPin.showModal()
    },
  },
  watch: {
    '$route' ( to ,before) {
      if(to.path === '/'){
        let _this = this
        setTimeout(()=>{
          _this.$router.push({
            path: before.path
          }, onComplete => {
          }, onAbort => {
          })
        },200)
      }else{
        this.flashCheckPath ()
      }
    },
    qsBackData: {
      handler(val) {
        if (this.curLoginType === 'UKEY') {
          let optWeb = val.optWeb
          if (optWeb === 1) {
            if (val.data.length === 1 && this.curDeviceId !== val.data[0].device_id) {
              this.numCount ++
              if(this.numCount >6){
                this.clearScanTimer ();
                this.logout()
                localStorage.setItem('interceptorMsg', '登陆UKey错误，请重新登录')
              }
            }
          } else if (optWeb === 4098) {
            this.numCount ++
            if(this.numCount >6){
              this.clearScanTimer ();
              this.logout()
              localStorage.setItem('interceptorMsg', '登陆UKey错误，请重新登录')
            }
          }
        }
      },
      deep: true,
      immediate: false
    },
  },
  mounted () {
    if (!window.qiankunStarted) {
      window.qiankunStarted = true;
      /*start({
          prefetch:true,//开启预加载
          sandbox:{
              experimentalStyleIsolation:true
          },
      });*/
      start()
    }

    this.flashCheckPath ()
    let _this = this
    //如果首次授权
    if(this.fristAuthUKey === 'true' && this.curLoginType === 'UKEY'){
      this.$refs.initUkeyAuth.showModal('init');
      return;
    }
    if( _this.defaultPsw === '1' ){
      _this.spinning = true
      //强制修改密码
      setTimeout(()=>{
        _this.showModal();
        _this.spinning = false
      },1000)

      return;
    }
    let roleIds = JSON.parse(sessionStorage.getItem('roleIds'))
    if(roleIds.length>0){
      _this.showFillScreen = roleIds[0] === 'ROLE_f70ec3e19e1e422a8e5d6d00c4eb1863' || roleIds[0] === 'ROLE_aec796fdc7295441ac4c138c061c4af3' || roleIds[0] === 'ROLE_anonymous';
    }
    /*this.iframe = document.getElementById('myiframe')
    let msg = sessionStorage.getItem('token')
    console.log('token值:'+msg)
    this.iframe.onload = function () {
        let param = {
            token: msg
        }
        console.log('token值2:'+param)
        this.iframe.contentWindow.postMessage(param,'*')
    }*/
    /*if( _this.isDefaultPinCode === 'true' ){
        //强制修改PIN码
        _this.showPinModal();
    }*/
    // this.checkPath ()
    /*      let data = sessionStorage.getItem('currentSelectIds')
          if(data !=='' && data !== undefined && data !== null){
              this.$store.dispatch('getCurrentSelectIds', data.split(','))
          }
          window.addEventListener('beforeunload', this.beforeunloadHandler('1'))*/
    //  子页面在mounted里面接受
    /*window.parent.postMessage('childLoaded','*')
    window.addEventListener('message',(e)=>{
        if(e.data){
            console.log('子页面接受父页面传来的消息')
            console.log(e.data)
            console.log(e)
        }
    },false)
*/

  },
  created () {
    this.init ()
    this.initPermission ()
    this.getSrceenObj ()
    document.getElementById('main').className = sessionStorage.getItem ('pageStyle')
    /*//  主页面在created里面下发传值
    let _this =this
    window.addEventListener('message',(e)=>{
        if(e.data === 'childLoaded'){
            console.log('父页面收到的数据')
            console.log(e.data)
            var iFrame = _this.$refs.myiframe;
            iFrame.contentWindow.postMessage( sessionStorage.getItem('token'),_this.iframeIp)
        }
    },false)*/
  },
  destroyed(){
    this.clearScanTimer ()
  },
}
</script>
<style rel="stylesheet/less" lang="less">
@import "~assets/main.less";
@import '~assets/styles/common.less';
@import '~assets/styles/table.less';
</style>
<style  rel="stylesheet/less"  lang="less">
#components-layout-demo-custom-trigger .trigger {
  font-size: 20px;
  line-height: 64px;
  padding: 0 24px;
  cursor: pointer;
  transition: color .3s;
  color: #464d5b;
}

#components-layout-demo-custom-trigger .logo {
  height: 35px;
  line-height: 35px;
  margin: 24px 16px;
  letter-spacing: 2px;
  font-weight: bold;
  color: #ffffff;
  text-align: center;
  font-size: 20px;
  font-family: "Microsoft YaHei";
  dl{
    width: 100%;
    dt{
      float: left;
      width: 35px; vertical-align: middle;
      margin-right: 10px;
      img{ width: 35px;}
    }
    dd{
      float: left; width: calc(100% - 45px); text-align: left;
    }
  }
}
.maxLogoCon{
  letter-spacing:1px !important; font-size: 18px !important;
  margin: 24px 0px !important;
  dl{
    dt{
      margin-right:2px !important;
    }
  }
}
.ant-layout-sider-collapsed{
  .maxLogoCon{
    dl{
      dt{
        margin-left: 20px !important;
        img{width: 28px !important;}
      }
    }
  }

}

</style>

